package com.sx.pipeline.ui.territory

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.FragTerritoryListBinding
import com.sx.pipeline.repos.http.req.DistrictBorderDTO
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.repos.http.res.TerritoryVO
import com.sx.pipeline.ui.territory.adapter.DistrictBorderListAdapter
import com.sx.pipeline.ui.territory.adapter.TerritoryListAdapter

/**
 * @Author: YY
 * @Date: 2022/8/3
 * @Desc: 区域列表
 */
class TerritoryTypeFragment: CYDataBindingBaseFragment<FragTerritoryListBinding, TerritoryVM>(R.layout.frag_territory_list),View.OnClickListener {

    private var position: Int = 0

    private lateinit var territoryAdapter: TerritoryListAdapter

    private lateinit var districtAdapter: DistrictBorderListAdapter

    companion object {
        fun newInstance(position: Int) =
            TerritoryTypeFragment().apply {
                arguments = Bundle().apply {
                    putInt(IntentKey.ID, position)
                }
            }
    }

    override fun initParam() {
        super.initParam()
        if (arguments != null) {
            arguments?.let {
                position = it.getInt(IntentKey.ID)
                if (position==3){
                    mBinding.btnAdd.visibility=View.VISIBLE
                }else{
                    mBinding.btnAdd.visibility=View.GONE
                }
            }
        }
    }

    override fun initListener() {
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {

            override fun onRefresh(refreshLayout: RefreshLayout) {
                mPage = 1
                if (position != 3) {
                    mViewModel.getTerritoryList(position, mPage)
                } else {
                    mViewModel.getDistrictBorderList(mPage)
                }
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (position != 3) {
                    mViewModel.getTerritoryList(position, mPage++)
                } else {
                    mViewModel.getDistrictBorderList(mPage++)
                }
            }
        })

    }

    override fun initData() {
        mViewModel.currentType=position
        mBinding.setVariable(BR.onClick, this)

    }

    override fun onResume() {
        super.onResume()
        if (position != 3) {
            mViewModel.getTerritoryList(position, mPage)
        } else {
            mViewModel.getDistrictBorderList(mPage)
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.autoRefreshEvent){
            mBinding.refreshLayout.autoRefresh()
        }
        observe(mViewModel.mUI.initRefreshEvent()) {
            mBinding.refreshLayout.finishRefresh(it!!)
        }
        observe(mViewModel.mUI.initLoadEvent()) {
            mBinding.refreshLayout.finishLoadMore(it!!)
        }

        observe(mViewModel.deleteTerritoryEvent) {
            mPage = 1
            if (position != 3) {
                mViewModel.getTerritoryList(position, mPage)
            } else {
                mViewModel.getDistrictBorderList(mPage)
            }
        }

        // 区域列表
        setTerritoryList()

        // 行政区域列表
        setDistrictList()
    }

    private fun setTerritoryList() {
        observe(mViewModel.territoryListEvent) {
            if (it != null && it.records.isNotEmpty()) {
                mBinding.emptyView.visibility = View.GONE
                mBinding.rvTerritory.visibility=View.VISIBLE
                mBinding.rvTerritory.layoutManager = LinearLayoutManager(
                    requireContext(), LinearLayoutManager.VERTICAL, false
                )
                territoryAdapter = TerritoryListAdapter(it.records as MutableList<TerritoryVO>)
                mBinding.rvTerritory.adapter = territoryAdapter

                territoryAdapter.setOnItemLongClickListener(object : OnItemLongClickListener {
                    override fun onItemLongClick(
                        adapter: BaseQuickAdapter<*, *>,
                        view: View,
                        position: Int
                    ): Boolean {
                        val territoryVO: TerritoryVO = adapter.data[position] as TerritoryVO
                        showDeleteDialog(territoryVO)
                        return true
                    }
                })
                territoryAdapter.setOnItemClickListener { adapter, view, position ->
                    val territoryVO: TerritoryVO = adapter.data[position] as TerritoryVO
                    RouteManager.Territory.intentToTerritoryDetails(position, territoryVO)
                }
//                if (!this::territoryAdapter.isInitialized) {
//
//                } else {
//                    if (mPage == 1) {
//                        mBinding.refreshLayout.setEnableRefresh(true)
//                        mBinding.rvTerritory.visibility=View.VISIBLE
//                        territoryAdapter.data=it.records as MutableList<TerritoryVO>
//                    } else {
//                        territoryAdapter.addData(it.records)
//                    }
//                }
                if (territoryAdapter.data.size == it.total) {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            } else {
                mBinding.refreshLayout.setEnableLoadMore(false)
//                mBinding.rvTerritory.adapter = null
                mBinding.emptyView.visibility = View.VISIBLE
                mBinding.rvTerritory.visibility=View.GONE
            }
        }
    }


    private fun setDistrictList() {
        mBinding.rvTerritory.layoutManager = LinearLayoutManager(
            requireContext(), LinearLayoutManager.VERTICAL, false
        )
        observe(mViewModel.districtBorderListEvent) {
            if (it != null && it.records.isNotEmpty()) {
                mBinding.emptyView.visibility = View.GONE
                mBinding.rvTerritory.visibility = View.VISIBLE
                districtAdapter = DistrictBorderListAdapter(it.records as MutableList<DistrictBorderDTO>)
                mBinding.rvTerritory.adapter = districtAdapter
                districtAdapter.setOnItemLongClickListener(object : OnItemLongClickListener {
                    override fun onItemLongClick(
                        adapter: BaseQuickAdapter<*, *>,
                        view: View,
                        position: Int
                    ): Boolean {
                        val dto: DistrictBorderDTO = adapter.data[position] as DistrictBorderDTO
                        showDeleteDistrictDialog(dto)
                        return true
                    }
                })
                districtAdapter.setOnItemClickListener { adapter, view, position ->
                    val dto: DistrictBorderDTO = adapter.data[position] as DistrictBorderDTO
                    // 行政区域
                    RouteManager.Main.intentToDistrictBorder(dto.name)
                }
//                if (!this::districtAdapter.isInitialized) {
//
//                } else {
//                    if (mPage == 1) {
//                        mBinding.rvTerritory.visibility = View.VISIBLE
//                        districtAdapter.setNewInstance(it.records as MutableList<DistrictBorderDTO>)
//                    } else {
//                        districtAdapter.addData(it.records)
//                    }
//                }
                if (districtAdapter.data.size == it.total) {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            } else {
                mBinding.refreshLayout.setEnableLoadMore(false)
                mBinding.rvTerritory.adapter = null
                mBinding.emptyView.visibility = View.VISIBLE
                mBinding.rvTerritory.visibility = View.GONE
            }
        }
    }

    /**
     * 长按删除
     */
    private fun showDeleteDialog(territoryVO: TerritoryVO ) {
        XPopup.Builder(requireContext())
            .asConfirm("提示",
                "是否删除《${territoryVO.name}》文件？"
            ) {
                mViewModel.deleteTerritory(territoryVO.id)
            }.show()
    }

    /**
     * 删除行政区域
     */
    private fun showDeleteDistrictDialog(dto: DistrictBorderDTO) {
        XPopup.Builder(requireContext())
            .asConfirm("提示",
                "是否删除《${dto.name}》文件？"
            ) {
                mViewModel.deleteDistrictBorder(dto.id)
            }.show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            //添加负责区域
            R.id.btn_add -> {
                mBinding.rvTerritory.visibility = View.VISIBLE
                showProvincesDialog()
            }
        }
    }


    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity(), true)
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                if("全部".equals(area)){
                    if("全部".equals(city)){
                        province
                    }else{
                        city
                    }
                }else{
                    area
                }?.let {
                    mViewModel.addAdministrative(provincesVO!!.id.toInt(), cityVO!!.id.toInt(), areaVO!!.id.toInt(), it
                    )
                }

            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(context).asCustom(popup).show()
    }
}